<template>
  <div class="user">
    <div class="searchDiv">
      <Form :model="searchItem" :label-width="80">
      <Row :gutter="10">
        <Col span="4">
             <FormItem label="用户名">
              <Input v-model="searchItem.userName" placeholder="请输入"></Input>
            </FormItem>
        </Col>
        <Col span="4">
            <FormItem label="真实姓名">
              <Input v-model="searchItem.realName" placeholder="请输入"></Input>
            </FormItem>
        </Col>
        <Col span="4">
            <FormItem label="手机号">
              <Input v-model="searchItem.tel" placeholder="请输入"></Input>
            </FormItem>
        </Col>
        <Col span="4">
            <FormItem label="所在部门">
              <Input v-model="searchItem.deptmentName" placeholder="请输入"></Input>
            </FormItem>

              <!-- <Select v-model="searchItem.department" clearable filterable>
                   <Option v-for="(item, index) in departmentList" :value="item.displayName" :key="index">{{item.displayName}}</Option>
               </Select> -->
        </Col>
        <Col span="4">
            <Button type="primary" @click="pageNo=1;getDataList()" class="chaxun">查询</Button>
            <Button type="success" @click="add">新增用户</Button>
        </Col>
       </Row>
      </Form>
    </div>
    <Table border :columns="columns" :loading="loading" :data="tableData" :no-data-text="loadingText ? loadingText : '暂无数据'"></Table>
    <Page show-total :total="total" :current="pageNo" :page-size="pageSize"  style="margin:20px auto;text-align:center" @on-change="changePage" show-elevator />
    <!-- 新增、编辑用户弹窗开始 -->
    <Modal :mask-closable="false" v-model="modal1" :title="title1">
      <Form :model="formItem" :label-width="80">
        <FormItem label="用户名">
              <Input v-model="formItem.userName" placeholder="请输入"></Input>
        </FormItem>
        <FormItem label="真实姓名">
              <Input v-model="formItem.realName" placeholder="请输入"></Input>
        </FormItem>
        <FormItem label="登录密码">
              <Input v-model="formItem.paw" type="password" placeholder="请输入"></Input>
        </FormItem>
         <FormItem label="确认密码">
              <Input v-model="formItem.paw2" type="password" placeholder="请输入"></Input>
        </FormItem>
        <FormItem label="所在部门">
           <Input v-model="formItem.deptmentName" placeholder="请输入"></Input>
              <!-- <Select v-model="formItem.departmentDictId" clearable filterable @on-change="bmChange">
                   <Option v-for="(item, index) in departmentList" :value="item.id" :key="index">{{item.displayName}}</Option>
               </Select> -->
              <!-- <Cascader :data="bmData" v-model="searchItem.department"></Cascader> -->
        </FormItem>
        <FormItem label="所属角色">
              <Select v-model="formItem.roleId">
                <Option v-for="item in roleList" :key="item.id" :value="item.id">{{item.name}}</Option>
            </Select>
        </FormItem>
        <FormItem label="手机号">
              <Input v-model="formItem.tel" placeholder="请输入"></Input>
        </FormItem>
        <FormItem label="E-mail">
              <Input v-model="formItem.email" placeholder="请输入"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
   	<Button type="text" size="large" @click="modal1=false">取消</Button>
   	<Button type="primary" size="large" :loading="btnClick" @click="ok">确定</Button>
   </div>
    </Modal>
    <!-- 新增、编辑角色弹窗结束 -->
    <!-- 设备授权弹窗开始 -->
    <Modal :mask-closable="false" v-model="modal2" title="设备授权" width="800">
       <div class="sbsq">用户名：{{sbqx.userName}}    真实姓名：{{sbqx.realName}}   所在部门：{{sbqx.department}}    系统角色：{{sbqx.role}}</div>
       <Table border :columns="columns2" :data="tableData2" :no-data-text="loadingText2 ? loadingText2 : '暂无数据'"></Table>
       <Page show-total :current="pageNo2" :total="total2" :page-size="pageSize2"  style="margin:20px auto;text-align:center" @on-change="changePage2" show-elevator />
    </Modal>
    <Modal :mask-closable="false" v-model="modal3" width="360" class-name="vertical-center-modal" @on-ok="remove(delID)">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-information-circle"></Icon>
            <span>确认删除</span>
        </p>
        <div style="text-align:center">
            <p>确认删除此数据么？</p>
        </div>
    </Modal>
    <!-- 设备授权弹窗结束 -->
  </div>
</template>

<script>

import {
  getTableData,
  getTableData2,
  add,
  update,
  del,
  update_status,
  assign,unAssign
} from '@/api/user'

import { getSelectOption } from '@/api/select'
import { getTableData as roleGetTableData } from '@/api/role'

export default {
  data () {
    return {
      btnClick:false,
      loading:true,
      departmentList:[],
      delID: 0,
      modal3: false,
      pageNo: 1,
      pageSize: 10,
      pageNo2: 1,
      pageSize2: 10,
      total: 0,
      total2: 0,
      loadingText: '',
      loadingText2: '',
      modal1: false,
      modal2: false,
      title1: '新增用户',
      msg1: '新增成功',
      isAdd: true,
      roleList: [],
      sbqx:{},
      searchItem: {
        userName: '',
        realName: '',
        tel: '',
        department: ''
      },
      formItem: {
        id: 0,
        userName: '',
        realName: '',
        tel: '',
        paw: '',
        deptmentName:'',
        departmentDictId: '',
        departmentDisplayName:'',
        departmentValue:'',
        roleId: 1,
        tel: '',
        email: ''
      },
      bmData: [
        {
          value: 'a',
          label: '技术部',
          children: [
            {
              value: 'a1',
              label: '技术一组'
            },
            {
              value: 'a2',
              label: '技术二组'
            },
            {
              value: 'a3',
              label: '技术三组'
            }
          ]
        }, {
          value: 'b',
          label: '市场部',
          children: [
            {
              value: 'b1',
              label: '市场推广',
              children: [
                {
                  value: 'b1-1',
                  label: '推广部一'
                }
              ]
            },
            {
              value: 'b2',
              label: '市场营销',
              children: [
                {
                  value: 'b2-1',
                  label: '营销部一'
                },
                {
                  value: 'b2-2',
                  label: '营销部二'
                }
              ]
            }
          ]
        }
      ],
      columns: [
        {
          type: 'index',
          width: 60,
          title: '序号',
          align: 'center'
        },
        {
          title: '用户名',
          key: 'userName'
        },
        {
          title: '真实姓名',
          key: 'realName'
        },
        {
          title: '所在部门',
          key: 'deptmentName'
        },
        {
          title: '所属角色',
          key: 'role'
        },
        {
          title: '手机号',
          key: 'tel'
        },
        {
          title: 'E-mail',
          key: 'email'
        },
        {
          title: '创建时间',
          key: 'creatTime'
        },
        {
          title: '状态',
          key: 'status',
          render: (h, params) => {
            return h('div', {}, params.row.status == 1 ? '开启' : '关闭')
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 250,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.edit(params.row)
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.setQx(params.row)
                    }
                  }
                },
                '设备授权'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.openDel(params.row.id)
                    }
                  }
                },
                '删除'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.statusChange(params.row)
                    }
                  }
                },
                params.row.status == 1 ? '关闭' : '开启'
              )
            ])
          }
        }
      ],
      tableData: [],
      /* tableData: [
        {
          userName: 'admin',
          realName: '李小明',
          department: '综合管理部',
          role: '系统管理员',
          tel: '13222221112',
          email: 'guojianpu@163.com',
          creatTime: '2016-10-03 12:23:32'
        },
        {
          userName: 'useadmin',
          realName: '王大锤',
          department: '综合管理部',
          role: '系统管理员',
          tel: '13222221112',
          email: 'guojianpu@163.com',
          creatTime: '2016-10-03 12:23:32'
        }
      ], */

      columns2: [
        {
          type: 'index',
          width: 60,
          title: '序号',
          align: 'center'
        },
        {
          title: '电站',
          key: 'powerStation'
        },
        {
          title: 'HD编号',
          key: 'hdNumber'
        },
        {
          title: '机组编号',
          key: 'aircrewNumber'
        },
        {
          title: '授权状态',
          key: 'state',
          render: (h, params) => {
            return h('div', {}, params.row.status == 1 ? '已授权' : '未授权')
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                        this.shouquan(params.row.status,params.row.adminId,params.row.equipmentId)
                    }
                  }
                },
                params.row.status == 1  ? '撤销授权' : '给予授权'
              )
            ])
          }
        }
      ],
      tableData2: []
    }
  },
  methods: {
    bmChange(e){
      var arry=this.departmentList.filter(item => item.id==e)
       this.formItem.departmentDisplayName=arry[0].displayName
       this.formItem.departmentValue=arry[0].value
    },
    getDepartment(){
      getSelectOption(
        {
          code: 'department'
        }
      ).then(res => {
        this.departmentList = res.data
      })
    },
    openDel (id) {
      this.modal3 = true
      this.delID = id
    },
    setQx (row) {
      console.log(row)
      this.modal2 = true;
      this.pageNo2=1;
      this.sbqx=row;
      this.getDataList2();
    },
    remove (id) {
      del({ id: id }).then(res => {
        if (res.code == 0) {
          this.$Message.info('删除成功')
          this.pageNo=1
          this.getDataList()
        } else {
          this.$Message.info(res.message)
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    add () {
      this.title1 = '新增用户'
      this.msg1 = '新增成功'
      this.isAdd = true
      this.formItem = {
        id: 0,
        userName: '',
        realName: '',
        tel: '',
        paw: '',
        departmentDictId: '',
        departmentDisplayName:'',
        departmentValue:'',
        roleId: 0,
        tel: '',
        email: ''
      }
      this.modal1 = true
    },
    edit (params) {
      this.title1 = '编辑用户'
      this.msg1 = '修改成功'
      this.isAdd = false
      // debugger

      this.formItem = params
      this.modal1 = true
    },
    ok () {
      this.btnClick=true
      var regemail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      var regphone= /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(19[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
      if (this.isAdd) {
        let params = {
          departmentDictId:this.formItem.departmentDictId,
        departmentDisplayName:this.formItem.departmentDisplayName,
        departmentValue:this.formItem.departmentValue,
        deptmentName:this.formItem.deptmentName,
          roleId: this.formItem.roleId,
          username: this.formItem.userName,
          password: this.formItem.paw,
          trueName: this.formItem.realName,
          mobile: this.formItem.tel,
          email: this.formItem.email
        }
        if(params.username.length<5||params.username.length>16){
          this.$Message.info('账号长度必须为5-16位')
          this.btnClick=false;
          return false;
      }
      if(params.password.length<4||params.password.length>16){
          this.$Message.info('密度长度必须为4-16位')
          this.btnClick=false;
          return false;
      }
      if(params.trueName==''||params.trueName==null||params.trueName==undefined){
          this.$Message.info('请输入真实姓名')
          this.btnClick=false;
          return false;
      }
      if(this.formItem.paw!=this.formItem.paw2){
          this.$Message.info('两次密码输入不一致')
          this.btnClick=false;
          return false;
      }
      if(!regphone.test(this.formItem.tel)){
          this.$Message.info('请输入正确的手机号')
          this.btnClick=false;
          return false;
      }
      if(!regemail.test(this.formItem.email)){
          this.$Message.info('请输入正确的邮箱地址')
          this.btnClick=false;
          return false;
      }

        add(params).then(res => {
          if (res.code == 0) {
            this.$Message.info('新增成功')
            this.modal1 = false
            this.btnClick=false;
          } else {
            this.$Message.info(res.message)
            this.btnClick=false;
          }
          this.getDataList()
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
        })
      } else {
        let params = {
          id: this.formItem.id,
          departmentDictId:this.formItem.departmentDictId,
        departmentDisplayName:this.formItem.departmentDisplayName,
        departmentValue:this.formItem.departmentValue,
        deptmentName:this.formItem.deptmentName,
          roleId: this.formItem.roleId,
          username: this.formItem.userName,
          password: this.formItem.paw,
          trueName: this.formItem.realName,
          mobile: this.formItem.tel,
          email: this.formItem.email
        }
        if(params.username.length<5||params.username.length>16){
          this.$Message.info('账号长度必须为5-16位')
          this.btnClick=false;
          return false;
      }
      if(params.password){
      if(params.password.length<4||params.password.length>16){
          this.$Message.info('密度长度必须为4-16位')
          this.btnClick=false;
          return false;
      }
       }
      if(params.trueName==''||params.trueName==null||params.trueName==undefined){
          this.$Message.info('请输入真实姓名')
          this.btnClick=false;
          return false;
      }
      if(this.formItem.paw!=this.formItem.paw2){
          this.$Message.info('两次密码输入不一致')
          this.btnClick=false;
          return false;
      }
      if(!regphone.test(this.formItem.tel)){
          this.$Message.info('请输入正确的手机号')
          this.btnClick=false;
          return false;
      }
      if(!regemail.test(this.formItem.email)){
          this.$Message.info('请输入正确的邮箱地址')
          this.btnClick=false;
          return false;
      }
        update(params).then(res => {
          if (res.code == 0) {
            this.$Message.info('修改成功')
            this.modal1 = false
            this.btnClick=false;
          } else {
            this.$Message.info(res.message)
            this.btnClick=false;
          }
          this.getDataList()
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
        })
      }

    },
    statusChange (row) {
      console.log('row>' + JSON.stringify(row))
      let status = 1
      let msg = '开启成功'
      /** 禁用 */
      if (row.status == 1) {
        status = 2
        msg = '关闭成功'
      }

      let params = {
        id: row.id,
        status: status
      }

      update_status(params).then(res => {
        if (res.code == 0) {
          this.$Message.info(msg)
        } else {
          this.$Message.info(res.message)
        }
        this.getDataList()
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    /** 分页 */
    changePage (pageNo) {
      this.pageNo = pageNo
      this.getDataList()
    },
     changePage2 (pageNo) {
      this.pageNo2 = pageNo
      this.getDataList2()
    },
    getDataList () {
      let params = {
        username: this.searchItem.userName,
        trueName: this.searchItem.realName,
        mobile: this.searchItem.tel,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        deptmentName:this.searchItem.deptmentName
      }
      this.loadingText = '数据加载中...'
      getTableData(params).then(res => {
        this.loading=false;
        if (res.code == 0) {
          this.total = res.data.total
          let list = res.data.list
          this.tableData = list.map(item => {
            let it = {}
            it.id = item.id
            it.userName = item.username
            it.realName = item.trueName

            // let role = ''
            // let roleIdStr = ''
            // let roleId = 0
            // if (item.roles) {
            //   item.roles.map(i => {
            //     role += i.name + ';'
            //     roleIdStr += i.id + ';'
            //   })
            //   role = role.substring(0, role.length - 1)
            //   roleIdStr = roleIdStr.substring(0, roleIdStr.length - 1)
            //   roleId = parseInt(roleIdStr)
            // }
            // it.role = role
            // it.roleId = roleId
            it.role=item.roles[0].name;
            it.roleId=item.roles[0].id;
            if (item.deptmentName) {
              it.deptmentName = item.deptmentName
            }

            it.tel = item.mobile
            it.email = item.email
            it.creatTime = item.createTime

            it.status = item.status
            return it
          })
          this.loadingText = ''
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    getDataList2 () {
      let params = {
        adminId: this.sbqx.id,
        pageNo: this.pageNo2,
        pageSize: this.pageSize2
      }
      this.loadingText = '数据加载中...'
      getTableData2(params).then(res => {
        if (res.code == 0) {
          this.total2 = res.data.total;
          this.tableData2=res.data.list;
          this.loadingText = ''
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    shouquan(status,adminId,equipmentId){
       let params = {
              adminId:this.sbqx.id,
              equipmentId: equipmentId
        }
       if(status=='1'){//取消授权
          unAssign(params).then(res => {
            if (res.code == 0) {
              this.$Message.info('取消授权成功')
              this.getDataList2();
            }
          }).catch(err => {
            console.error('err>' + JSON.stringify(err))
          })
       } else {//给予授权
           assign(params).then(res => {
            if (res.code == 0) {
              this.$Message.info('授权成功')
              this.getDataList2();
            }
          }).catch(err => {
            console.error('err>' + JSON.stringify(err))
          })
       }
    }
  },
  mounted () {},
  created () {
    this.getDepartment();
    this.getDataList()

    let params = {
      pageNo: 1,
      pageSize: 100
    }
    roleGetTableData(params).then(res => {
      console.log('res>' + JSON.stringify(res))
      if (res.code == 0) {
        this.roleList = res.data.list
      }
    }).catch(err => {
      console.error('err>' + JSON.stringify(err))
    })
  }
}
</script>

<style lang="less">
.user {
  background: #fff;
  height: 100%;
  padding: 15px;
  font-size: 14px;
  .searchDiv {
    .chaxun {
      margin-right: 15px;
    }
  }
}
.sbsq {
  font-size:15px;
  padding-bottom:10px;
}

</style>
